#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/19  12:22
# @Author: 余浪人
# @email: yulangren520@gmail.com
import jieba
import jieba.analyse
from apps.control import sys_bp
from flask_login import login_required
from flask import request, render_template, jsonify, url_for
from apps.forms.content_form import TL_Content_Form, TL_Column_Form
from apps.lib.cache_sys import cache
from apps.lib.public import add_data, fake_delete_data, edit_data, check_obj, real_delete_data, recover_data, \
    real_deletes, fake_deletes, recover_datas, page_auto, add_tag
from apps.lib.token import Verify_authorization
from apps.models.content_model import db, TL_Column_model, TL_Content_Model


# *******************************  分类/内容操作  ***********************************
# 发布内容
@sys_bp.route('/content_add', endpoint='content_add', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def content_add():
    if request.method == 'POST':
        keyword = ','.join(jieba.cut_for_search(request.form['title'])) if not request.form['keyword'] else None
        keys = [x for x, _ in jieba.analyse.textrank(request.form['title'], withWeight=True)]
        add_tag(keys)
        cache.delete('index_page')
        return add_data(TL_Content_Model, TL_Content_Form, db, {'keyword': keyword})
    return render_template('system_template/content.html', form=TL_Content_Form())


# 内容列表
@sys_bp.route('/content_list', endpoint='content_list', methods=['GET', 'DELETE', 'DELETES'])
@login_required
def content_list():
    if request.method == 'DELETE':
        return fake_delete_data(TL_Content_Model, db, request.form.get('uid'))
    elif request.method == 'DELETES':
        return fake_deletes(TL_Content_Model, db, request.form.get('id_array').split('#TL#'))
    search = request.args.get('search', '')
    if search:
        data_list, page = page_auto(
            TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status != -1, TL_Content_Model.title.like(f"%{search}%")))
    else:
        data_list, page = page_auto(TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status != -1))
    return render_template('system_template/content_list.html', data_list=data_list, page=page)


# 内容修改
@sys_bp.route('/content_edit_<int:id>', endpoint='content_edit', methods=['GET', 'POST'])
@login_required
def content_edit(id):
    con_obj = TL_Content_Model.query.filter_by(id=id).first()
    if request.method == 'POST' and not check_obj(con_obj):
        cache.delete(f'view/{url_for("webapp_bp.article_page", uid=con_obj.uuid)}')
        return edit_data(TL_Content_Form, TL_Content_Model, db, id)
    if not check_obj(con_obj):
        return render_template('system_template/content.html', form=TL_Content_Form(data=dict(con_obj)))


# 内容回收站
@sys_bp.route('/content_recycle_list', endpoint='content_recycle_list', methods=['GET', 'DELETE', 'RECOVER', 'DELETES', 'RECOVERS'])
@login_required
def content_recycle_list():
    if request.method == 'DELETE':
        return real_delete_data(TL_Content_Model, db, request.form.get('uid'))
    elif request.method == 'RECOVER':
        return recover_data(TL_Content_Model, db, request.form.get('uid'))
    elif request.method == 'DELETES':
        return real_deletes(TL_Content_Model, db, request.form.get('id_array').split('#TL#'))
    elif request.method == 'RECOVERS':
        return recover_datas(TL_Content_Model, db, request.form.get('id_array').split('#TL#'))
    data_list, page = page_auto(TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == -1))
    return render_template('system_template/content_recycle_list.html', data_list=data_list, page=page)


# 分类添加
@sys_bp.route('/column_add', endpoint='column_add', methods=['GET', 'POST'])
@login_required
@Verify_authorization
def column_add():
    if request.method == 'POST':
        return add_data(TL_Column_model, TL_Column_Form, db)
    return render_template('system_template/column.html', form=TL_Column_Form())


@sys_bp.route('/column_list', endpoint='column_list', methods=['GET', 'DELETE', "DELETES"])
@login_required
def column_list():
    if request.method == 'DELETE':
        id = request.form.get('uid')
        if TL_Column_model.query.filter(TL_Column_model.column_parent_id == id).count():
            return jsonify({"status": 1, "msg": "请先移除子栏目!"})
        elif TL_Content_Model.query.filter(TL_Content_Model.superior == id).count():
            return jsonify({"status": 1, "msg": "请先移除栏目内容!(含:回收站)"})
        return real_delete_data(TL_Column_model, db, id)
    elif request.method == 'DELETES':
        idList = request.form.get('id_array').split('#TL#')
        for id in idList:
            if TL_Column_model.query.filter(TL_Column_model.column_parent_id == id).count():
                return jsonify({"status": 1, "msg": "请先移除子栏目!"})
            elif TL_Content_Model.query.filter(TL_Content_Model.superior == id).count():
                return jsonify({"status": 1, "msg": "请先移除栏目内容!(含:回收站)"})
            return real_delete_data(TL_Column_model, db, id)
    data_list, page = page_auto(TL_Column_model.query.order_by(TL_Column_model.id.desc()))
    return render_template('system_template/column_list.html', data_list=data_list, page=page)


@sys_bp.route('/column_edit<int:id>', endpoint='column_edit', methods=['GET', 'POST'])
@login_required
def column_edit(id):
    col_obj = TL_Column_model.query.filter_by(id=id).first()
    if request.method == 'POST' and not check_obj(col_obj):
        cache.delete(f'view/{request.host_url}list_article/{col_obj.uuid}')
        return edit_data(TL_Column_Form, TL_Column_model, db, id)
    if not check_obj(col_obj):
        return render_template('system_template/column.html', form=TL_Column_Form(data=dict(col_obj)))
